package com.heima.wemedia.filter;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.heima.wemedia.util.WmThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WmTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.校验请求是否来源于网关
        if (!StrUtil.equals(request.getHeader("X-Request-From"), "heima-leadnews-wemedia-gateway")) {
            response.setStatus(HttpStatus.HTTP_BAD_REQUEST);
            return false;
        }
        //2.获得userId
        if (ObjectUtil.isNotEmpty(request.getHeaders("userId"))) {
            WmThreadLocalUtil.setUserId(Convert.toSBC(request.getHeader("userId")));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WmThreadLocalUtil.clear();
    }
}
